package org.example.day12;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 5.1.5.1: 方法scheduleAtFixedRate(TimerTask task,Date firstTime,long period)
 */
public class MyThread13 {
    private static Timer timer = new Timer();
    private static int runCount = 0;
    static public class MyTask1 extends TimerTask{
        @Override
        public void run() {
            try {
                System.out.println("task1 begin, time = " + new Date());
                Thread.sleep(4000);
                System.out.println("task1 end, time = " + new Date());
                runCount++;
                if(runCount == 5){
                    timer.cancel();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        try {
            MyTask1 task1 = new MyTask1();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateString1 = "2022-05-16 11:09:00";
            Date dateRef = sdf.parse(dateString1);
            System.out.println("字符串时间为: " + dateRef.toLocaleString() + " 当前时间: " + new Date().toLocaleString());
//            timer.schedule(task1,dateRef,3000);
            timer.scheduleAtFixedRate(task1,dateRef,3000);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}
